package web.video;

import bean.Video;
import com.alibaba.fastjson.JSON;
import entity.TypeEntity;
import entity.UserEntity;
import entity.VideoEntity;
import util.FANREN;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name = "VideoEdit",urlPatterns = "/dao/update/videoEdit")
public class VideoEdit extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String jsonString = FANREN.getJson(request);
        EntityManager em = (EntityManager) request.getAttribute("_entity.Manager");
        Video video = JSON.parseObject(jsonString,Video.class);
        VideoEntity v = null;
        if(video.getVid().equals("")) {
            //新增
            v = new VideoEntity();
            v.setViews("0");
            v.setImgUrl("");
        } else {
            v = em.find(VideoEntity.class,Integer.parseInt(video.getVid()));
        }
        Query query = em.createNativeQuery("select tid from TypeEntity where name = ?");
        query.setParameter(1, video.getType());
        List list = query.getResultList();
        TypeEntity typeEntity = em.find(TypeEntity.class, list.get(0));

        query = em.createNativeQuery("select uid from UserEntity where name = ?");
        query.setParameter(1, video.getAuthor());
        list = query.getResultList();
        UserEntity userEntity = null;
        if(list.size()==0){//新增
            throw new RuntimeException();
        }else {//取
            userEntity = em.find(UserEntity.class, list.get(0));
        }
        v.setAv(video.getAv());
        v.setTid(typeEntity);
        v.setUid(userEntity);
        v.setName(video.getName());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        v.setTime(sf.format(new Date( )));
        v.setIntroduce(video.getIntroduce());
        em.persist(v);
    }
}
